<script lang="ts" setup>
import type { ConsumptionRecordsApi } from '#/api/spa/consumption-records';
import type { VxeTableInstance } from '#/adapter/vxe-table';

import { Page, useVbenModal } from '@vben/common-ui';
import { cloneDeep, formatDateTime } from '@vben/utils';
import {
  Button,
  message,
  Tabs,
  Pagination,
  Form,
  RangePicker,
  DatePicker,
  Select,
  Input,
} from 'ant-design-vue';
import { DictTag } from '#/components/dict-tag';
import ConsumptionRecordsForm from './modules/form.vue';
import { Download, Plus, RefreshCw, Search, Trash2 } from '@vben/icons';
import { ContentWrap } from '#/components/content-wrap';
import { VxeColumn, VxeTable } from '#/adapter/vxe-table';
import { TableToolbar } from '#/components/table-toolbar';
import { useTableToolbar } from '#/hooks';

import { ref, h, reactive, onMounted, nextTick } from 'vue';
import { $t } from '#/locales';
import { isEmpty } from '@vben/utils';
import {
  getConsumptionRecordsPage,
  deleteConsumptionRecords,
  deleteConsumptionRecordsList,
  exportConsumptionRecords,
} from '#/api/spa/consumption-records';
import { downloadFileFromBlobPart } from '@vben/utils';

import { getRangePickerDefaultProps } from '#/utils';

const loading = ref(true); // 列表的加载中
const list = ref<ConsumptionRecordsApi.ConsumptionRecords[]>([]); // 列表的数据

const total = ref(0); // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  handCardId: undefined,
  memberId: undefined,
  roomNumber: undefined,
  serviceType: undefined,
  serviceName: undefined,
  quantity: undefined,
  unitPrice: undefined,
  totalAmount: undefined,
  discountAmount: undefined,
  actualAmount: undefined,
  technicianId: undefined,
  consumptionTime: undefined,
  status: undefined,
  paymentMethod: undefined,
  remarks: undefined,
  createTime: undefined,
});
const queryFormRef = ref(); // 搜索的表单
const exportLoading = ref(false); // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true;
  try {
    const params = cloneDeep(queryParams) as any;
    if (params.consumptionTime && Array.isArray(params.consumptionTime)) {
      params.consumptionTime = (params.consumptionTime as string[]).join(',');
    }
    if (params.createTime && Array.isArray(params.createTime)) {
      params.createTime = (params.createTime as string[]).join(',');
    }
    const data = await getConsumptionRecordsPage(params);
    list.value = data.list;
    total.value = data.total;
  } finally {
    loading.value = false;
  }
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields();
  handleQuery();
};

const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: ConsumptionRecordsForm,
  destroyOnClose: true,
});

/** 创建消费记录 */
function handleCreate() {
  formModalApi.setData({}).open();
}

/** 编辑消费记录 */
function handleEdit(row: ConsumptionRecordsApi.ConsumptionRecords) {
  formModalApi.setData(row).open();
}

/** 删除消费记录 */
async function handleDelete(row: ConsumptionRecordsApi.ConsumptionRecords) {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deleting', [row.id]),
    duration: 0,
    key: 'action_process_msg',
  });
  try {
    await deleteConsumptionRecords(row.id as number);
    message.success({
      content: $t('ui.actionMessage.deleteSuccess', [row.id]),
      key: 'action_process_msg',
    });
    await getList();
  } finally {
    hideLoading();
  }
}

/** 批量删除消费记录 */
async function handleDeleteBatch() {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deleting'),
    duration: 0,
    key: 'action_process_msg',
  });
  try {
    await deleteConsumptionRecordsList(checkedIds.value);
    checkedIds.value = [];
    message.success($t('ui.actionMessage.deleteSuccess'));
    await getList();
  } finally {
    hideLoading();
  }
}

const checkedIds = ref<number[]>([]);
function handleRowCheckboxChange({
  records,
}: {
  records: ConsumptionRecordsApi.ConsumptionRecords[];
}) {
  checkedIds.value = records.map((item) => item.id);
}

/** 导出表格 */
async function onExport() {
  try {
    exportLoading.value = true;
    const data = await exportConsumptionRecords(queryParams);
    downloadFileFromBlobPart({ fileName: '消费记录.xls', source: data });
  } finally {
    exportLoading.value = false;
  }
}

/** 初始化 */
const { hiddenSearchBar, tableToolbarRef, tableRef } = useTableToolbar();
onMounted(() => {
  getList();
});
</script>

<template>
  <Page auto-content-height>
    <FormModal @success="getList" />

    <ContentWrap v-if="!hiddenSearchBar">
      <!-- 搜索工作栏 -->
      <Form :model="queryParams" ref="queryFormRef" layout="inline">
        <Form.Item label="手牌ID" name="handCardId">
          <Input
            v-model:value="queryParams.handCardId"
            placeholder="请输入手牌ID"
            allowClear
            @pressEnter="handleQuery"
            class="w-full"
          />
        </Form.Item>
        <Form.Item label="会员ID" name="memberId">
          <Input
            v-model:value="queryParams.memberId"
            placeholder="请输入会员ID"
            allowClear
            @pressEnter="handleQuery"
            class="w-full"
          />
        </Form.Item>
        <Form.Item label="房间号" name="roomNumber">
          <Input
            v-model:value="queryParams.roomNumber"
            placeholder="请输入房间号"
            allowClear
            @pressEnter="handleQuery"
            class="w-full"
          />
        </Form.Item>
        <Form.Item label="服务类型" name="serviceType">
          <Select
            v-model:value="queryParams.serviceType"
            placeholder="请选择服务类型"
            allowClear
            class="w-full"
          >
            <Select.Option label="请选择字典生成" value="" />
          </Select>
        </Form.Item>
        <Form.Item label="服务名称" name="serviceName">
          <Input
            v-model:value="queryParams.serviceName"
            placeholder="请输入服务名称"
            allowClear
            @pressEnter="handleQuery"
            class="w-full"
          />
        </Form.Item>
        <Form.Item label="数量" name="quantity">
          <Input
            v-model:value="queryParams.quantity"
            placeholder="请输入数量"
            allowClear
            @pressEnter="handleQuery"
            class="w-full"
          />
        </Form.Item>
        <Form.Item label="单价" name="unitPrice">
          <Input
            v-model:value="queryParams.unitPrice"
            placeholder="请输入单价"
            allowClear
            @pressEnter="handleQuery"
            class="w-full"
          />
        </Form.Item>
        <Form.Item label="总金额" name="totalAmount">
          <Input
            v-model:value="queryParams.totalAmount"
            placeholder="请输入总金额"
            allowClear
            @pressEnter="handleQuery"
            class="w-full"
          />
        </Form.Item>
        <Form.Item label="优惠金额" name="discountAmount">
          <Input
            v-model:value="queryParams.discountAmount"
            placeholder="请输入优惠金额"
            allowClear
            @pressEnter="handleQuery"
            class="w-full"
          />
        </Form.Item>
        <Form.Item label="实收金额" name="actualAmount">
          <Input
            v-model:value="queryParams.actualAmount"
            placeholder="请输入实收金额"
            allowClear
            @pressEnter="handleQuery"
            class="w-full"
          />
        </Form.Item>
        <Form.Item label="技师ID" name="technicianId">
          <Input
            v-model:value="queryParams.technicianId"
            placeholder="请输入技师ID"
            allowClear
            @pressEnter="handleQuery"
            class="w-full"
          />
        </Form.Item>
        <Form.Item label="消费时间" name="consumptionTime">
          <RangePicker
            v-model:value="queryParams.consumptionTime"
            v-bind="getRangePickerDefaultProps()"
            class="w-full"
          />
        </Form.Item>
        <Form.Item label="状态" name="status">
          <Select
            v-model:value="queryParams.status"
            placeholder="请选择状态"
            allowClear
            class="w-full"
          >
            <Select.Option label="请选择字典生成" value="" />
          </Select>
        </Form.Item>
        <Form.Item label="支付方式" name="paymentMethod">
          <Input
            v-model:value="queryParams.paymentMethod"
            placeholder="请输入支付方式"
            allowClear
            @pressEnter="handleQuery"
            class="w-full"
          />
        </Form.Item>
        <Form.Item label="备注" name="remarks">
          <Input
            v-model:value="queryParams.remarks"
            placeholder="请输入备注"
            allowClear
            @pressEnter="handleQuery"
            class="w-full"
          />
        </Form.Item>
        <Form.Item label="创建时间" name="createTime">
          <RangePicker
            v-model:value="queryParams.createTime"
            v-bind="getRangePickerDefaultProps()"
            class="w-full"
          />
        </Form.Item>
        <Form.Item>
          <Button class="ml-2" @click="resetQuery"> 重置 </Button>
          <Button class="ml-2" @click="handleQuery" type="primary">
            搜索
          </Button>
        </Form.Item>
      </Form>
    </ContentWrap>

    <!-- 列表 -->
    <ContentWrap title="消费记录">
      <template #extra>
        <TableToolbar
          ref="tableToolbarRef"
          v-model:hidden-search="hiddenSearchBar"
        >
          <Button
            class="ml-2"
            :icon="h(Plus)"
            type="primary"
            @click="handleCreate"
            v-access:code="['spa:consumption-records:create']"
          >
            {{ $t('ui.actionTitle.create', ['消费记录']) }}
          </Button>
          <Button
            :icon="h(Download)"
            type="primary"
            class="ml-2"
            :loading="exportLoading"
            @click="onExport"
            v-access:code="['spa:consumption-records:export']"
          >
            {{ $t('ui.actionTitle.export') }}
          </Button>
          <Button
            :icon="h(Trash2)"
            type="primary"
            danger
            class="ml-2"
            :disabled="isEmpty(checkedIds)"
            @click="handleDeleteBatch"
            v-access:code="['spa:consumption-records:delete']"
          >
            批量删除
          </Button>
        </TableToolbar>
      </template>
      <vxe-table
        ref="tableRef"
        :data="list"
        show-overflow
        :loading="loading"
        @checkboxAll="handleRowCheckboxChange"
        @checkboxChange="handleRowCheckboxChange"
      >
        <vxe-column type="checkbox" width="40"></vxe-column>
        <vxe-column field="id" title="主键ID" align="center" />
        <vxe-column field="handCardId" title="手牌ID" align="center" />
        <vxe-column field="memberId" title="会员ID" align="center" />
        <vxe-column field="roomNumber" title="房间号" align="center" />
        <vxe-column field="serviceType" title="服务类型" align="center" />
        <vxe-column field="serviceName" title="服务名称" align="center" />
        <vxe-column field="quantity" title="数量" align="center" />
        <vxe-column field="unitPrice" title="单价" align="center" />
        <vxe-column field="totalAmount" title="总金额" align="center" />
        <vxe-column field="discountAmount" title="优惠金额" align="center" />
        <vxe-column field="actualAmount" title="实收金额" align="center" />
        <vxe-column field="technicianId" title="技师ID" align="center" />
        <vxe-column field="consumptionTime" title="消费时间" align="center">
          <template #default="{ row }">
            {{ formatDateTime(row.consumptionTime) }}
          </template>
        </vxe-column>
        <vxe-column field="status" title="状态" align="center" />
        <vxe-column field="paymentMethod" title="支付方式" align="center" />
        <vxe-column field="remarks" title="备注" align="center" />
        <vxe-column field="createTime" title="创建时间" align="center">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </vxe-column>
        <vxe-column field="operation" title="操作" align="center">
          <template #default="{ row }">
            <Button
              size="small"
              type="link"
              @click="handleEdit(row as any)"
              v-access:code="['spa:consumption-records:update']"
            >
              {{ $t('ui.actionTitle.edit') }}
            </Button>
            <Button
              size="small"
              type="link"
              danger
              class="ml-2"
              @click="handleDelete(row as any)"
              v-access:code="['spa:consumption-records:delete']"
            >
              {{ $t('ui.actionTitle.delete') }}
            </Button>
          </template>
        </vxe-column>
      </vxe-table>
      <!-- 分页 -->
      <div class="mt-2 flex justify-end">
        <Pagination
          :total="total"
          v-model:current="queryParams.pageNo"
          v-model:page-size="queryParams.pageSize"
          show-size-changer
          @change="getList"
        />
      </div>
    </ContentWrap>
  </Page>
</template>
